#####################################################################
## Replication file for                                           
## When Do Citizens Consider Political Parties Legitimate?  
##                                   
## Author: Ann-Kristin Kölln (ann-kristin.kolln@gu.se)                                                     
## 26th May 2023                                                 
##                
#####################################################################


# R version 4.3.0 (2023-04-21) -- "Already Tomorrow"; Platform: x86_64-apple-darwin20 (64-bit)


## load experimental data on party legitimacy perceptions
data<-read.csv("PartyLeg_exp.csv", header=TRUE)

## install and load required packages
install.packages(c("ltm", "psych","ggplot2", "sjPlot", "tidyr", "plyr"))

library(ltm)
library(psych)
library(sjPlot)
library(tidyr)
library(ggplot2)
library(plyr)


## evaluating legitimacy index

# inter-item corrleations
Leg<-data[c("Leg_SameRights", "Leg_DiscussProposals", "Leg_AcceptDecisions")]
cor(Leg, use = "pairwise.complete.obs")

# calculating Cronbach's alpha
cronbach.alpha (Leg, na.rm=TRUE)

# PCA
LegNA<-na.omit(Leg)
LegNA.pca<-prcomp(LegNA, center = TRUE, scale =TRUE)
summary(LegNA.pca)
LegNA.pca$rotation

# descriptives of legitimacy index
mean(data$Leg_01, na.rm=T)
sd(data$Leg_01, na.rm=T)



## creating input for Figure 2

data$treat_mod <-as.factor(data$treat_mod)
data$treat_mod <- factor(data$treat_mod, levels = c("control", "centre", "moderate left/right","left/right wing"))


#model results
fit1b<-lm(Leg_SameRights ~ treat_mod,data=data) #Q4_1a = item 1 of PartyLeg index, scaled 0-1
fit2b<-lm(Leg_DiscussProposals ~ treat_mod,data=data)
fit3b<-lm(Leg_AcceptDecisions ~ treat_mod,data=data)
fit4b<-lm(Leg_01~ treat_mod,data=data) ##Leg_01 = final index

#store predicted values
simdat2<-expand.grid("treat_mod"=c("control","centre", "moderate left/right","left/right wing"))
p1b<-predict(fit1b,simdat2,se.fit=T)
p2b<-predict(fit2b,simdat2,se.fit=T)
p3b<-predict(fit3b,simdat2,se.fit=T)
p4b<-predict(fit4b,simdat2,se.fit=T)

namedat2<-expand.grid("treat_mod"=c("control","centre", "moderate left/right","left/right wing"))

#put all into the same dataframe
plot.dat2<-gather(data.frame("SameRights"=p1b$fit,"DiscussProposals"=p2b$fit,"AcceptDecisions"=p3b$fit,"Index"=p4b$fit, namedat2),key="variable",value="fit",-treat_mod)
plot.dat2<-cbind(plot.dat2,"se"=c(p1b$se.fit, p2b$se.fit, p3b$se.fit, p4b$se.fit))
plot.dat2$variable<-factor(plot.dat2$variable,levels=c("SameRights","DiscussProposals","AcceptDecisions","Index"))

#function to rotate axis
rotatedAxisElementText = function(angle,position='x'){
  angle     = angle[1]; 
  position  = position[1]
  positions = list(x=0,y=90,top=180,right=270)
  if(!position %in% names(positions))
    stop(sprintf("'position' must be one of [%s]",paste(names(positions),collapse=", ")),call.=FALSE)
  if(!is.numeric(angle))
    stop("'angle' must be numeric",call.=FALSE)
  rads  = (angle - positions[[ position ]])*pi/180
  hjust = 3.75*(1 - sin(rads))
  vjust = 0.65*(1 + cos(rads))
  element_text(angle=angle,vjust=vjust,hjust=hjust)
}

#pd <- position_jitter(width = 0.1, height = 0)
pd <- position_dodge(width =.1)



## creating Figure 2
p2<-ggplot(plot.dat2,aes(treat_mod, fit, group=variable, colour=variable,label=fit)) +
  geom_point(aes(shape=variable),position=pd,size=2) + 
  geom_text(aes(y=fit-1.96*se,label=format(round(fit,2),nsmall = 2)),hjust="middle", vjust=2,size=1.75) +
  facet_grid(~variable)+
  geom_linerange(aes(ymin=fit-1.96*se, ymax=fit+1.96*se)) + 
  xlab("") + 
  ylab("Party legitimacy perceptions (0-1)") +
  theme(panel.background = element_blank(), axis.line = element_line(colour = "black"),
        panel.border=element_rect(linetype = "solid", fill = NA),
        strip.background = element_rect(color="black",linetype="solid"),legend.position = "none",text = element_text(size=rel(3.5)),
        strip.text.x=element_text(size=10),axis.text.x = rotatedAxisElementText(45,'x'))+
  scale_color_manual(values=c("grey60","grey60","grey60","black")) +
  scale_shape_manual(values=rep(19,5))
  
jpeg("Figure2.jpeg", width=8, height=5, units='in', res=300)   
p2
dev.off()




## creating input for Figure 3

data$treat_demo <-as.factor(data$treat_demo)
data$treat_demo <- factor(data$treat_demo, levels = c("control", "pro-democratic", "anti-democratic"))

#model results
fit1<-lm(Leg_SameRights ~treat_demo,data=data) #Q4_1a = item 1 of PartyLeg index, scaled 0-1
fit2<-lm(Leg_DiscussProposals ~ treat_demo,data=data)
fit3<-lm(Leg_AcceptDecisions ~ treat_demo,data=data)
fit4<-lm(Leg_01~ treat_demo,data=data) ##Leg_01 = final index

#store predicted values
simdat<-expand.grid("treat_demo"=c("control","pro-democratic","anti-democratic"))
p1<-predict(fit1,simdat,se.fit=T)
p2<-predict(fit2,simdat,se.fit=T)
p3<-predict(fit3,simdat,se.fit=T)
p4<-predict(fit4,simdat,se.fit=T)

namedat<-expand.grid("treat_demo"=c("control","pro-democratic","anti-democratic"))

#put all into the same dataframe
plot.dat<-gather(data.frame("SameRights"=p1$fit,"DiscussProposals"=p2$fit,"AcceptDecisions"=p3$fit,"Index"=p4$fit,namedat),key="variable",value="fit",-treat_demo)
plot.dat<-cbind(plot.dat,"se"=c(p1$se.fit,p2$se.fit,p3$se.fit,p4$se.fit))
plot.dat$variable<-factor(plot.dat$variable,levels=c("SameRights","DiscussProposals","AcceptDecisions","Index"))

#pd <- position_jitter(width = 0.1, height = 0)
pd <- position_dodge(width =.1)


## creating Figure 3
p<-ggplot(plot.dat,aes(treat_demo, fit, group=variable, colour=variable,label=fit)) +
  geom_point(aes(shape=variable),position=pd,size=2) + 
  geom_text(aes(y=fit-1.96*se,label=format(round(fit,2),nsmall = 2)),hjust="middle", vjust=2,size=1.75) +
  facet_grid(~variable)+
  geom_linerange(aes(ymin=fit-1.96*se, ymax=fit+1.96*se)) + 
  xlab("") + 
  ylab("Party legitimacy perceptions (0-1)") +
  theme(panel.background = element_blank(), axis.line = element_line(colour = "black"),
        panel.border=element_rect(linetype = "solid", fill = NA),
        strip.background = element_rect(color="black",linetype="solid"),legend.position = "none",text = element_text(size=rel(3.5)),
        strip.text.x=element_text(size=10),axis.text.x = rotatedAxisElementText(45,'x'))+
  scale_color_manual(values=c("grey60","grey60","grey60","black")) +
  scale_shape_manual(values=rep(19,5))
  
jpeg("Figure3.jpeg", width=8, height=5, units='in', res=300)   
p
dev.off()




#### Supplementary Information ####

## Part E, main survey ##


## ideological moderation

# producing input for Table E9
data$treat_ideol <-as.factor(data$treat_ideol)
data$treat_ideol <- factor(data$treat_ideol, levels = c("control", "left-wing", "centre-left", "centre", "centre-right", "right-wing"))

ddply(data, ~treat_ideol, summarise, mean = mean(PercIdeol, na.rm=TRUE), sd = sd(PercIdeol, na.rm = TRUE), N = length(PercIdeol))

# differences in perceived ideology
fit_ideol_manip<- aov(PercIdeol~ treat_ideol, data= data)
summary(fit_ideol_manip)

TukeyHSD(fit_ideol_manip)


## democratic behavior

#producing input for Table E10
ddply(data, ~treat_demo, summarise, mean = mean(PercDemnorm, na.rm=TRUE), sd = sd(PercDemnorm, na.rm = TRUE), N = length(PercDemnorm))

# differences in perceived democratic behavior
fit_demo_manip<- aov(PercDemnorm ~ treat_demo, data= data)
summary(fit_demo_manip)

TukeyHSD(fit_demo_manip)



## Part F ##


## produce Table F1
tab_model(fit1b, fit2b, fit3b, fit4b, show.r2= FALSE, emph.p= FALSE, show.ci=FALSE, show.se= TRUE, file ="TableF1.doc")

## produce Table F2
fit4b<-lm(Leg_01~ data$treat_ideol,data=data) 
tab_model(fit4b, show.r2= FALSE, emph.p= FALSE, show.ci=FALSE, show.se= TRUE, file ="TableF2.doc")

## produce Table F3
tab_model(fit1, fit2, fit3, fit4, show.r2= FALSE, emph.p= FALSE, show.ci=FALSE, show.se= TRUE, file ="TableF3.doc")


## create input for Table F4

data$treat_demo2<-factor(data$treat_demo, levels = c("control", "pro-democratic", "anti-democratic"))

data$treat_demo3[data$treat_demo2 == "control"]<-"control"
data$treat_demo3[data$treat_demo2 == "pro-democratic" & data$PercDemnorm >4]<-"pro-democratic"
data$treat_demo3[data$treat_demo2 == "anti-democratic"]<-"anti-democratic"

data$treat_demo3 <-as.factor(data$treat_demo3)
data$treat_demo3 <- factor(data$treat_demo3, levels = c("control", "pro-democratic", "anti-democratic"))

#model results
fit1d<-lm(Leg_01 ~ treat_demo3,data=data)

# produce Table F4
tab_model(fit1d, show.r2= FALSE, emph.p= FALSE, show.ci=FALSE, show.se= TRUE, file ="TableF4.doc")



## create input for Table F5

data_mod<-data[c("Leg_01", "treat_mod", "threat")]
data_mod<-na.omit(data_mod)

data_demo<-data[c("Leg_01", "treat_demo3", "threat")]
data_demo<-na.omit(data_demo)


fit_dv_mod<-lm(Leg_01 ~ treat_mod + threat, data= data_mod)
fit_mediator_threat2 <-lm(threat ~ treat_mod, data= data_mod)

fit_dv_demo<-lm(Leg_01 ~ treat_demo3 + threat, data= data_demo)
fit_mediator_threat <-lm(threat ~ treat_demo3, data= data_demo)

# producing Table F5
tab_model(fit_dv_mod, fit_mediator_threat2, fit_dv_demo, fit_mediator_threat, show.r2= TRUE, emph.p= FALSE, show.ci=FALSE, show.se= TRUE, file ="TableF5.doc")


## create input for Table F6

data$treat_mod2 <- factor(data$treat_mod, levels = c("centre", "moderate left/right","left/right wing"))
data$treat_mod2<-droplevels(data$treat_mod2)

data$treat_demo4 <- factor(data$treat_demo3, levels = c("pro-democratic", "anti-democratic"))
data$treat_demo4<-droplevels(data$treat_demo4)


fit_model1<-lm(Leg_01 ~ treat_mod2, data= data)
fit_model2<-lm(Leg_01 ~ treat_demo4, data= data)

# producing Table F5
tab_model(fit_model1, fit_model2, show.r2= TRUE, emph.p= FALSE, show.ci=FALSE, show.se= TRUE, file ="TableF6.doc")
